<?php

namespace App\Console\Commands;

use App\Models\Balance;
use App\Models\Withdraw;
use App\Services\BalanceService;
use Illuminate\Console\Command;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Exceptions\GatewayException;

class QueryWithdrawStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'query_withdraw_status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '查询提现进行中的状态';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $start_at = date('Y-m-d H:i:s', time() - 30);
        $pay = Pay::alipay();
        Withdraw::where('status', Withdraw::STATUS_ING)->where('updated_at', '<=', $start_at)->chunk(20, function ($list) use($pay){
            foreach ($list as $model) {
                try {
                    $response =  $pay->find(['out_biz_no' => $model->trade_no, 'product_code' => 'TRANS_ACCOUNT_NO_PWD'
                        , 'biz_scene' => 'DIRECT_TRANSFER'], 'transfer');
                    \DB::transaction(function () use($model, $response) {
                        $model->status = Withdraw::STATUS_SUCCESS;
                        $model->out_order_id = $response->order_id;
                        $model->reason = $response->status;
                        $model->save();
                        BalanceService::store($model->benefit_user, 0, $model->merchant_id, -$model->amount, Balance::TYPE_WITHDRAW, 0, '', '', false, $model->id);
                    });

                } catch (GatewayException $e) {
                    $msg = $e->raw['alipay_fund_trans_order_query_response']['sub_msg'];
                    $model->status = Withdraw::STATUS_FAIL;
                    $model->reason = $msg;
                    $model->save();
                }
            }
        });
    }
}

